﻿'use strict';

var direction = {
    Left: "Left",
    Right: "Right"
};

$(document).ready(function () {
    ExecuteOrDelayUntilScriptLoaded(GetTasks, "sp.js");
});

function taskTitleKeyup() {
    switch (event.keyCode) {
        // Handle the Enter button to call button click                        
        case 13: $('#addTaskButton').click();
            break;
            // Handle the ESC key press to clear value                        
        case 27: $(this).val('');
            break;
    }
}
function addNewTask() {
    var title = $('#newTaskTitle').val();
    var desc = $('#newTaskDesc').val();

    if (title == '') {
        alert('Please enter a value for the Title.');
        $('#newTaskTitle').focus();
    } else {
        AddNewTask(title, desc);
    }
}

function editTaskSaveButton(taskElement) {
    updateTask(taskElement);
}

function editTaskCancelButton(taskElement) {
    var taskListItemElement = $(taskElement).parents("li:first");
    taskListItemElement.children('div.editDiv').hide();
    taskListItemElement.children('div.taskDetailDiv').show();
}

function editTask(taskElement) {
    var taskElement = $(taskElement);
    taskElement.children('div.taskDetailDiv').hide();
    taskElement.children('div.editDiv').show();
    var title = taskElement.find('p.taskTitle').text();
    var description = taskElement.find('p.taskDescription').text();

    taskElement.find('input.editTaskTitle').val(title);
    taskElement.find('textarea.editTaskDescription').text(description);
}

function deleteButton(element) {
    $(element).siblings('.confirmDelete').show();
    $(element).hide();
}

function noDeleteButton(element) {
    $(element).parent('.confirmDelete').hide();
    $(element).parent().siblings('.deleteButton').show();
}

function yesDeleteButton(element) {
    deleteTask(element);
}

function updateTask(taskElement) {
    var taskListItemElement = $(taskElement).parents("li:first");
    var taskTitleElement = taskListItemElement.find('input.editTaskTitle');
    var updatedTitle = taskTitleElement.val();

    if (updatedTitle == '') {
        alert('Please enter a value for the task title');
        taskTitleElement.focus();
        return;
    }

    var updatedDescription = taskListItemElement.find('textarea.editTaskDescription').text();
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(taskListName);
    var taskId = taskListItemElement.data('taskId');
    var listItem = list.getItemById(taskId);

    listItem.set_item('Title', updatedTitle);
    listItem.set_item('Body', updatedDescription);

    listItem.update();

    GetTasks();
}

function AddNewTask(taskName, taskDesc) {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(taskListName);
    var listItemInfo = new SP.ListItemCreationInformation();
    var listItem = list.addItem(listItemInfo);

    listItem.set_item('Title', taskName);
    if(taskDesc != '')
        listItem.set_item('Body', taskDesc);
    listItem.update();

    context.executeQueryAsync(AddTaskSuccess, AddTaskFail);
}

function AddTaskSuccess() {
    GetTasks();
    $('#newTaskTitle').val('');
    $('#newTaskTitle').focus();
}

function AddTaskFail(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


function deleteTask(taskElement) {
    var taskListItemElement = $(taskElement).parents("li:first");
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(taskListName);
    var taskId = taskListItemElement.data('taskId');
    var itemToDelete = list.getItemById(taskId);
    itemToDelete.deleteObject();

    context.executeQueryAsync(DeleteTaskSuccess, DeleteTaskFail);
}

function DeleteTaskSuccess() {
    GetTasks();
}

function DeleteTaskFail(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

var tasks;
var taskListName = "Tasks";

function ChangeStatus(taskElement, moveDirection) {
    taskElement = $(taskElement);
    var taskListItemElement;

    if (taskElement.is('li')) {
        taskListItemElement = taskElement;
    } else {
        taskListItemElement = $(taskElement).parents("li:first");
    }

    var updatedStatus = GetNewStatus(taskListItemElement, moveDirection);
    if (updatedStatus == null) {
        return;
    }

    updateTaskStatus(taskListItemElement.data('taskId'), updatedStatus);
    GetTasks();
}

function GetNewStatus(element, moveDirection) {
    var currentStatus = element.data("status");

    var newStatus = null;

    if (moveDirection == direction.Left) {
        newStatus = GetLeftStatus(currentStatus);
    }
    else if (moveDirection == direction.Right) {
        newStatus = GetRightStatus(currentStatus);
    };

    return newStatus;
}

function GetLeftStatus(currentStatus) {
    var newStatus = null;
    switch (currentStatus) {
        case "In Progress": newStatus = "Not Started";
            break;
        case "Completed": newStatus = "In Progress";
            break;
    }
    return newStatus;
}

function GetRightStatus(currentStatus) {
    var newStatus = null;
    switch (currentStatus) {
        case "Not Started": newStatus = "In Progress";
            break;
        case "In Progress": newStatus = "Completed";
            break;
    }
    return newStatus;
}

function updateTaskStatus(id, status) {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(taskListName);
    var listItem = list.getItemById(id);
    listItem.set_item('Status', status);
    listItem.update();
}

function GetTasks() {

    // -----------------For Host Web-----------------
    //var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    //var currentcontext = new SP.ClientContext.get_current();
    //var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
    //var web = hostcontext.get_web();

    //var list = web.get_lists().getByTitle(taskListName);
    //tasks = list.getItems('');
    //currentcontext.load(tasks, 'Include(ID,Title,Body,Status)');
    //currentcontext.executeQueryAsync(OnGetTasksSucceeded, OnGetTasksFailed);

    // -----------------For Host Web-----------------

    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(taskListName);
    tasks = list.getItems('');
    context.load(tasks, 'Include(ID,Title,Body,Status)');
    context.executeQueryAsync(OnGetTasksSucceeded, OnGetTasksFailed);
}

function OnGetTasksSucceeded() {
    $('.taskDiv>ul').empty();

    var taskCollection = tasks.getEnumerator();
    while (taskCollection.moveNext()) {
        var task = taskCollection.get_current();
        var taskList = GetTaskListElementByTaskStatus(task.get_item('Status'));
        if (taskList != null) {
            addTaskToList(taskList, task.get_item('ID'), task.get_item('Title'), task.get_item('Body'), task.get_item('Status'));
        }
    }
}

function OnGetTasksFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function GetTaskListElementByTaskStatus(status) {
    //dealing with only three status as of now

    var taskList;

    switch (status) {
        case "Not Started": taskList = $('#notStartedTasksDiv>ul');
            break;
        case "In Progress": taskList = $('#inProgressTasksDiv>ul');
            break;
        case "Completed": taskList = $('#completedTasksDiv>ul');
            break;
        default:
            taskList = null;
    }

    return taskList;

}

function addTaskToList(list, id, title, description, status) {
    var itemTemplate = $('#TemplateListItem').clone();

    itemTemplate.attr('id', null);
    itemTemplate.find('.taskTitle').text(title);
    itemTemplate.find('.taskDescription').html(description);

    itemTemplate.data('status', status);
    itemTemplate.data('taskId', id);

    switch (status) {
        case "Not Started": itemTemplate.find('.moveLeftButton').hide();
            break;
        case "Completed": itemTemplate.find('.moveRightButton').hide();
            break;
    }

    list.append(itemTemplate);
}

function updateTask(taskElement) {
    var taskListItemElement = $(taskElement).parents("li:first");
    var taskTitleElement = taskListItemElement.find('input.editTaskTitle');
    var updatedTitle = taskTitleElement.val();
    if (updatedTitle == '') {
        alert('Please enter a value for the Task Title');
        taskTitleElement.focus();
        return;
    }
    var updatedDescription = taskListItemElement.find('textarea.editTaskDescription').text();
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(taskListName);

    var taskId = taskListItemElement.data('taskId');

    var listItem = list.getItemById(taskId);

    listItem.set_item('Title', updatedTitle);
    listItem.set_item('Body', updatedDescription);
    listItem.update();

    GetTasks();
}

function ChangeStatus(taskElement, moveDirection) {
    var taskListItemElement = $(taskElement).parents("li:first");
    var updatedStatus = GetNewStatus(taskListItemElement, moveDirection);

    if (updatedStatus == null) {
        return;
    }
    updateTaskStatus(taskListItemElement.data('taskId'), updatedStatus);
    GetTasks();
}

function updateTaskStatus(id, status) {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle(taskListName);
    var listItem = list.getItemById(id);
    listItem.set_item('Status', status);

    listItem.update();
}

function GetNewStatus(element, moveDirection) {
    var currentStatus = element.data("status");

    var newStatus = null;
    if (moveDirection == direction.Left) {
        newStatus = GetLeftStatus(currentStatus);
    }
    else if (moveDirection == direction.Right) {
        newStatus = GetRightStatus(currentStatus);
    };

    return newStatus;
}

function GetLeftStatus(currentStatus) {
    var newStatus = null;
    switch (currentStatus) {
        case "In Progress": newStatus = "Not Started";
            break;
        case "Completed": newStatus = "In Progress";
            break;
    }
    return newStatus;
}

function GetRightStatus(currentStatus) {
    var newStatus = null;
    switch (currentStatus) {
        case "Not Started": newStatus = "In Progress";
            break;
        case "In Progress": newStatus = "Completed";
            break;
    }
    return newStatus;
}

function getQueryStringParameter(paramToRetrieve) {
    var params =
    document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}